package com.yc.springmvc;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    //前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if (session.getAttribute("loginedUser") == null) {
            //工程的路径前缀  contextPath  /SpringMvc
            String contextPath = request.getServletContext().getContextPath();
            String indexPath = contextPath + "/index.html";
            response.sendRedirect(indexPath);   //浏览器端解析  若加/ 则是从8080后面拼接
            //阻止请求到达目标资源
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    //后置拦截
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("===================================postHandle=======================================");
    }

    //完成拦截
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("===================================afterHandle=======================================");
    }
}
